package theadPerMessage;


import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class ThreadPerMessageDemo {

    public void accept() {
         try {
           // jdk21:  ExecutorService scheduler = Executors.newVirtualThreadPerTaskExecutor();
           final ServerSocketChannel ssc = ServerSocketChannel.open().bind(new InetSocketAddress(8086));
             while(true) {
                 SocketChannel sc = ssc.accept();
                 new Thread(
                 // jdk21: scheduler.submit(
                         () -> {
                             try {
                                 ByteBuffer rb = ByteBuffer.allocate(1024);
                                 sc.read(rb);
                                 // 休息0.5秒
                                 Thread.sleep(2000);
                                 log.info(">>>this.thread:{}", Thread.currentThread().getName());

                                 String http = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello";
                                 sc.write(ByteBuffer.wrap(http.getBytes()));
//                                 ByteBuffer wb = (ByteBuffer) rb.flip();
//                                 sc.write(wb);
                                 // 关闭socket
                                 sc.close();
                             } catch (Exception e) {
                                 throw new RuntimeException(e);
                             }
                         }
                 );
             }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ThreadPerMessageDemo demo = new ThreadPerMessageDemo();
        demo.accept();
    }
}
